<template>
  <div class="version-status-transition">
    <!-- 状态流转操作区 -->
    <el-card class="transition-card">
      <template #header>
        <div class="card-header">
          <span>状态流转</span>
          <el-button 
            type="text" 
            size="small" 
            @click="refreshReadiness"
            :loading="readinessLoading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 当前状态 -->
      <div class="current-status">
        <el-tag :type="getStatusType(currentStatus)" size="large">
          {{ getStatusName(currentStatus) }}
        </el-tag>
      </div>

      <!-- 完成度显示 -->
      <div v-if="completionData" class="completion-section">
        <div class="completion-title">版本完成度</div>
        <div class="completion-overall">
          <el-progress 
            :percentage="Math.round(completionData.overall_completion * 100)" 
            :status="getCompletionStatus(completionData.overall_completion)"
            :stroke-width="20"
          />
          <div class="completion-details">
            <div class="detail-item">
              <span>任务：</span>
              <span>{{ Math.round(completionData.task_completion * 100) }}%</span>
              <span class="count">({{ completionData.details.tasks.completed }}/{{ completionData.details.tasks.total }})</span>
            </div>
            <div class="detail-item">
              <span>需求：</span>
              <span>{{ Math.round(completionData.requirement_completion * 100) }}%</span>
              <span class="count">({{ completionData.details.requirements.completed }}/{{ completionData.details.requirements.total }})</span>
            </div>
            <div class="detail-item">
              <span>缺陷：</span>
              <span>{{ Math.round(completionData.defect_completion * 100) }}%</span>
              <span class="count">({{ completionData.details.defects.resolved }}/{{ completionData.details.defects.total }})</span>
            </div>
            <div class="detail-item">
              <span>测试：</span>
              <span>{{ Math.round(completionData.test_completion * 100) }}%</span>
              <span class="count">({{ completionData.details.tests.passed }}/{{ completionData.details.tests.total_run }})</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 自动流转提示 -->
      <el-alert
        v-if="hasAutoTransition"
        type="info"
        :closable="false"
        show-icon
        class="auto-transition-alert"
      >
        <template #title>
          <span>满足条件时将自动流转状态</span>
        </template>
      </el-alert>

      <!-- 允许的流转操作 -->
      <div class="transition-actions">
        <div class="actions-title">可执行的操作</div>
        <div class="action-buttons">
          <el-button
            v-for="transition in allowedTransitions"
            :key="transition.to_status"
            :type="getTransitionButtonType(transition)"
            :disabled="!canTransition"
            @click="handleTransition(transition)"
          >
            {{ transition.name }}
          </el-button>
        </div>
      </div>

      <!-- 流转准备情况 -->
      <div v-if="transitionReadiness && transitionReadiness.readiness.length > 0" class="readiness-section">
        <div class="readiness-title">流转准备情况</div>
        <div 
          v-for="readiness in transitionReadiness.readiness" 
          :key="readiness.target_status"
          class="readiness-item"
        >
          <div class="readiness-header">
            <span class="target-status">{{ getStatusName(readiness.target_status) }}</span>
            <el-tag :type="readiness.is_ready ? 'success' : 'warning'" size="small">
              {{ readiness.is_ready ? '已满足' : '未满足' }}
            </el-tag>
          </div>
          <ul v-if="!readiness.is_ready && readiness.unmet_conditions.length > 0" class="unmet-conditions">
            <li v-for="(condition, index) in readiness.unmet_conditions" :key="index">
              {{ condition }}
            </li>
          </ul>
        </div>
      </div>
    </el-card>

    <!-- 状态流转对话框 -->
    <VersionTransitionDialog
      v-model="dialogVisible"
      :version-id="versionId"
      :transition="currentTransition"
      :completion-data="completionData"
      @success="handleTransitionSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import versionAPI from '@/api/version'
import type {
  VersionCompletion,
  VersionTransitionRule,
  VersionTransitionReadiness
} from '@/types/version'
import { usePermission } from '@/hooks/usePermission'
import { useVersionStates } from '@/composables/useVersionStates'
import VersionTransitionDialog from './VersionTransitionDialog.vue'

interface Props {
  versionId: string
  currentStatus: string
}

const props = defineProps<Props>()

const { hasPermission } = usePermission()
const { getStateByCode, getStateName } = useVersionStates()

const completionData = ref<VersionCompletion | null>(null)
const allowedTransitions = ref<VersionTransitionRule[]>([])
const transitionReadiness = ref<VersionTransitionReadiness | null>(null)
const dialogVisible = ref(false)
const currentTransition = ref<VersionTransitionRule | null>(null)
const loading = ref(false)
const readinessLoading = ref(false)

// 计算属性
const canTransition = computed(() => {
  return hasPermission('version:transition_request') || hasPermission('version:update')
})

const hasAutoTransition = computed(() => {
  return allowedTransitions.value.some(t => t.auto_trigger)
})

// 加载数据
const loadCompletion = async () => {
  try {
    loading.value = true
    const data = await versionAPI.getCompletion(props.versionId)
    completionData.value = data
  } catch (error) {
    console.error('获取完成度失败:', error)
    ElMessage.error('获取版本完成度失败')
  } finally {
    loading.value = false
  }
}

const loadAllowedTransitions = async () => {
  try {
    const response = await versionAPI.getAllowedTransitions(props.versionId)
    allowedTransitions.value = response.allowed_transitions || []
  } catch (error) {
    console.error('获取允许的流转列表失败:', error)
    ElMessage.error('获取允许的流转列表失败')
  }
}

const loadTransitionReadiness = async () => {
  try {
    readinessLoading.value = true
    const data = await versionAPI.getTransitionReadiness(props.versionId)
    transitionReadiness.value = data
  } catch (error) {
    console.error('获取流转准备情况失败:', error)
  } finally {
    readinessLoading.value = false
  }
}

const refreshReadiness = async () => {
  await Promise.all([
    loadCompletion(),
    loadTransitionReadiness()
  ])
}

// 处理状态流转
const handleTransition = (transition: VersionTransitionRule) => {
  currentTransition.value = transition
  dialogVisible.value = true
}

const handleTransitionSuccess = () => {
  dialogVisible.value = false
  // 刷新数据
  refreshReadiness()
  loadAllowedTransitions()
  // 通知父组件刷新
  emit('statusChanged')
}

// 状态相关方法
const getStatusType = (status: string): 'success' | 'info' | 'warning' | 'danger' | 'primary' => {
  // 从状态管理系统动态获取状态类型
  const state = getStateByCode(status)
  if (state?.color) {
    // 将颜色转换为 Element Plus 的 tag type
    const colorMap: Record<string, 'success' | 'info' | 'warning' | 'danger' | 'primary'> = {
      '#67C23A': 'success',
      '#52c41a': 'success',
      '#E6A23C': 'warning',
      '#faad14': 'warning',
      '#F56C6C': 'danger',
      '#ff4d4f': 'danger',
      '#409EFF': 'primary',
      '#1890ff': 'primary',
      '#909399': 'info',
      '#8c8c8c': 'info',
      '#d9d9d9': 'info'
    }
    for (const [color, type] of Object.entries(colorMap)) {
      if (state.color.toLowerCase() === color.toLowerCase()) {
        return type
      }
    }
  }
  // 如果状态管理系统没有颜色，根据状态名称判断
  if (state?.name) {
    const statusName = state.name.toLowerCase()
    if (statusName.includes('发布') || statusName.includes('完成') || statusName.includes('成功')) {
      return 'success'
    }
    if (statusName.includes('测试') || statusName.includes('评审') || statusName.includes('警告')) {
      return 'warning'
    }
    if (statusName.includes('废弃') || statusName.includes('失败') || statusName.includes('错误')) {
      return 'danger'
    }
    if (statusName.includes('开发') || statusName.includes('进行')) {
      return 'primary'
    }
  }
  return 'info'
}

const getStatusName = (status: string) => {
  // 从状态管理系统动态获取状态名称
  return getStateName(status) || status
}

const getTransitionButtonType = (transition: VersionTransitionRule) => {
  if (transition.require_approval) {
    return 'warning'
  }
  if (transition.auto_trigger) {
    return 'info'
  }
  return 'primary'
}

const getCompletionStatus = (completion: number) => {
  if (completion >= 0.98) return 'success'
  if (completion >= 0.75) return ''
  return 'exception'
}

const emit = defineEmits<{
  statusChanged: []
}>()

// 监听状态变化
watch(() => props.currentStatus, () => {
  loadAllowedTransitions()
  loadTransitionReadiness()
})

// 初始化
onMounted(() => {
  loadCompletion()
  loadAllowedTransitions()
  loadTransitionReadiness()
})
</script>

<style scoped lang="scss">
.version-status-transition {
  .transition-card {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .current-status {
    margin-bottom: 20px;
    text-align: center;
  }

  .completion-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    .completion-title {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
      color: #303133;
    }

    .completion-overall {
      .completion-details {
        margin-top: 12px;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
        font-size: 13px;

        .detail-item {
          display: flex;
          align-items: center;
          gap: 4px;

          .count {
            color: #909399;
            font-size: 12px;
          }
        }
      }
    }
  }

  .auto-transition-alert {
    margin-bottom: 20px;
  }

  .transition-actions {
    margin-bottom: 20px;

    .actions-title {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
      color: #303133;
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }

  .readiness-section {
    .readiness-title {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
      color: #303133;
    }

    .readiness-item {
      margin-bottom: 16px;
      padding: 12px;
      background: #fafafa;
      border-radius: 4px;

      .readiness-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .target-status {
          font-weight: 500;
        }
      }

      .unmet-conditions {
        margin: 8px 0 0 0;
        padding-left: 20px;
        color: #606266;
        font-size: 13px;

        li {
          margin-bottom: 4px;
        }
      }
    }
  }
}
</style>

